import React from 'react';
import {Tabs,Button,Select,Input,message,Table,AutoComplete,Popconfirm,Row,Col} from 'antd';
import {injectIntl} from 'react-intl';
import UserChargeReported from '../data/userChargeReported';
import CarChargeReport from '../data/carChargeReport';
import DepChargeReport from '../data/depChargeReport';
import Grid from '../../components/table/grid';
import ChargeProcess from '../order/chargeProcess'
import axios from 'axios'
import {sessionManager} from "../../utils/sessionStorage";
import SCModal from '../../components/pickCity/SCModal';

const TabPane = Tabs.TabPane;
const Option = Select.Option;
class ledgerRules extends React.Component {
	constructor(props) {
		super(props);
		const common = this.props.intl.messages.common;
		const panes = [];
		this.state = {
			panes,
			activeKey:'1',
			refresh:0,
			checkedRefresh:0,
			params:{
				stubGroupId:''
			},
			checkedDetailParams:{
				id:'' //已审核分账规则编号
			},
			operationDetailsVisible:false,
			checkStatus:null,
			checkedRuleInfo:{},
			checkStatusDiv:'',
			checkedDesc:'',
			redoBtn:'',
			editableDataCopy:[],
			btnDisabled:false,
			count:0

		};
		this.columns = [
			{
				title:'分账内容',
				dataIndex: 'billTypeName',
				key: 'billTypeName',
				width: 120,
			},
			{
				title: '分账区间',
				dataIndex: 'splitPeriodName',
				key: 'splitPeriodName',
				width: 120,
			},
			{
				title: '分账人账号',
				dataIndex: 'billUserAccount',
				key: 'billUserAccount',
				width: 150,
			},
			{
				title: '分账人姓名',
				dataIndex: 'billUserName',
				key: 'billUserName',
				width: 150,
			},
			{
				title: '分账模式',
				dataIndex: 'expressionTypeName',
				key: 'expressionTypeName',
				width: 150,
			},
			{
				title: '表达式',
				dataIndex: 'expressionInfo',
				key: 'expressionInfo',
			}

		];
		this.columns2= [
			{
				title:'分账内容',
				dataIndex: 'billTypeName',
				key: 'billTypeName',
			},
			{
				title: '分账区间',
				dataIndex: 'splitPeriodName',
				key: 'splitPeriodName',
			},
			{
				title: '分账人账号',
				dataIndex: 'billUserAccount',
				key: 'billUserAccount',
			},
			{
				title: '分账人姓名',
				dataIndex: 'billUserName',
				key: 'billUserName',
			},
			{
				title: '分账模式',
				dataIndex: 'expressionTypeName',
				key: 'expressionTypeName',
			},
			{
				title: '表达式',
				dataIndex: 'expressionInfo',
				key: 'expressionInfo',
			}

		];
		this.checkedColumns = [
			{
				title:'审核状态',
				key: 'checkStatus',
				width: 120,
				render:(text)=>{
					switch (text.checkStatus) {
						case 0:
							return '待审核';
						case 1:
							return '审核通过';
						case 2:
							return '审核不通过';
						case 3:
							return '撤销';
						default :
							break
					}
				}
			},
			{
				title:'桩群名',
				dataIndex: 'stubGroupName',
				key: 'stubGroupName',
				width: 250,
			},
			{
				title:'提交人',
				dataIndex: 'applyUserName',
				key: 'applyUserName',
				width: 120,
			},
			{
				title:'提交时间',
				dataIndex: 'applyTime',
				key: 'applyTime',
				width: 200,
			},
			{
				title:'审核人',
				dataIndex: 'adminName',
				key: 'adminName',
				width: 250,
			},
			{
				title:'审核时间',
				dataIndex: 'checkTime',
				key: 'checkTime',
				width: 200,
			},
			{
				title:'操作',
				key: 'operation',
				width: 120,
				render: (text, record) => {
					return (
						<span>
							<a onClick={() => this.showModel(text)}>查看详情</a>
                		</span>
					)
				},
			},
		];
		console.log(<Select/>);
		this.editableColumns = [
			{
				title:'分账内容',
				key: 'billType',
				width: 200,
				render:(text,record,index)=>{
					return(
						<Select value={text.billType + ''}  onChange={(e)=>this.handleChange(e,'billType' ,record,index)}>
							<Option value="0">电费</Option>
							<Option value="1">服务费</Option>
						</Select>
					)
				}
			},
			{
				title: '分账区间',
				key: 'splitPeriod',
				width: 200,
				render:(text,record,index)=>{
					return(
						<Select  value={text.splitPeriod+'' }  onChange={(e)=>this.handleChange(e,'splitPeriod' ,record,index)}>
							<Option value="2">尖时</Option>
							<Option value="1">峰时</Option>
							<Option value="4">平时</Option>
							<Option value="3">谷时</Option>
						</Select>
					)
				}
			},
			{
				title: '分账人账号',
				key: 'billUserAccount',
				width: 200,
				render:(text,record,index)=>{
					if(text.billUserAccount==''){
						return(
							<AutoComplete placeholder="" onBlur={(val)=> this.checkAccount(val,'billUserAccount',index)}
										  defaultValue={text.billUserAccount} disabled={this.state.hasBillUserId} />
						)
					}else{
						return text.billUserAccount
					}
				}
			},
			{
				title: '分账人姓名',
				key: 'billUserName',
				width: 200,
				render:(text,record,index)=>{
					console.log('---> ' + text.billUserName);
					if(text.billUserName===''){
						return(
							<AutoComplete placeholder="需要验证账号是否存在" onBlur={(val)=>this.checkAccount(val,'billUserName',index)} defaultValue={text.billUserName} disabled={this.state.hasBillUserName}/>
						)
					}else{
						return <Input value={text.billUserName} disabled={true} />
					}
				}
			},
			{
				title: '分账模式',
				key: 'expressionType',
				width: 200,
				render:(text,record,index)=>{
					return(
						<Select  value={text.expressionType+''}  onChange={(e)=>this.handleChange(e,'expressionType' ,record,index)}>
							<Option value="2">按比例</Option>
							<Option value="1">按固定金额</Option>
						</Select>
					)
				}
			},
			{
				title: '表达式',
				key: 'expressionInfo',
				width: 200,
				render:(text,record,index)=>{
					return(
						<Input type={'number'} id={'expressionInfo'} value={text.expressionInfo} onChange={(e) => this.InputChange(e, 'expressionInfo', record, index)}/>
					)
				}
			},
			{
				title:'操作',
				key: 'operation',
				width: 150,
				render: (text, record,index) => {
					return (
						<Popconfirm title="确定删除?" onConfirm={() => this.deleteRowdata(text,record.unique,index)}>
							<a href="javascript:;">删除</a>
						</Popconfirm>
					)
				},
			},

		];
	}

	handleChange(e,text,record,index){
		console.log(e);
		// let row=`editableDataCopy[${index}].${text}`;
		let roeObject = `editableDataCopy[${index}]`;
		this.state.editableDataCopy[index][text] = e;
		this.setState({
			// [row]:e.key,
			// [roeObject]:Object.assign(this.state.editableDataCopy[index], {[text]:e})
      editableDataCopy: this.state.editableDataCopy
		}, () => {
			this.addTabPane();
		});
		// this.state.editableDataCopy

	}
	checkAccount(value,text,index){
		if (!value || !value.trim()) {
			return;
		}
		let roeObject = `editableDataCopy[${index}]`;
		if(text=='billUserAccount'){
			axios.get('/api/stubGroup/billSplit/checkBillUser',{params:{
					account:value.trim()
				}}).then(res=>{
				if(res&&res.data){
					sessionManager.set('billUserName',res.data.name);
          const dataSource = [...this.state.editableDataCopy];
					dataSource[index].billUserName = res.data.name;
					console.log(res.data.name);
					console.log(dataSource);
          this.setState({
            editableDataCopy: dataSource,
						hasBillUserId:!!res.id,
						[roeObject]:Object.assign(this.state.editableDataCopy[index], {[text]:value})
					}, () => {
          	this.addTabPane();
					});
				}
			})

		}else if(text=='billUserName'){
			value=sessionManager.get('billUserName');
			this.setState({
				hasBillUserName:!!sessionManager.get('billUserName'),
				[roeObject]:Object.assign(this.state.editableDataCopy[index], {[text]:value})
			});
		}else{
			this.setState({
				[roeObject]:Object.assign(this.state.editableDataCopy[index], {[text]:value})
			});
		}
	}

	InputChange=(e,text,record,index)=>{
    this.state.editableDataCopy[index][text] = Number(e.target.value || 0);
    this.setState({
      // [row]:e.key,
      // [roeObject]:Object.assign(this.state.editableDataCopy[index], {[text]:e})
      editableDataCopy: this.state.editableDataCopy
    }, () => {
      this.addTabPane();
    });
	}
	componentWillMount() {
		if(this.props.location.state&&this.props.location.state.stubGroupId){
			this.setState({
				params:{
					stubGroupId:this.props.location.state.stubGroupId
				}
			})
		}else{
			this.setState({
				params:{
					stubGroupId:sessionManager.get('stubGroupId')||''
				}
			})
		}

	}
	getCheckedInfo(){
		axios.get('/api/stubGroup/billSplit/CheckedInfoDetail',{ params:{id: this.state.checkedDetailParams.id}}).then(res => {
			console.log('checkedRuleInfo',res)
			if(res&&res.data){
				this.setState({
					checkedRuleInfo: res.data
				},()=>{
					let checkedDesc,redoBtn;
					let checkStatusDiv;
					switch(this.state.checkStatus){
						case 0:
							redoBtn=<Button type="primary" onClick={this.redoBill}>撤回</Button>;
							checkStatusDiv='待审核';
							break;
						case 1:
							checkStatusDiv='审核通过';
							break
						case 2:
							checkedDesc=<div className="wrongText padBT-10">审核不通过说明： {this.state.checkedRuleInfo.checkResult}</div>
							checkStatusDiv='审核不通过';
							break
						case 3:
							checkStatusDiv='撤销';
							break
						default:
							break
					}
					this.setState({
						checkStatusDiv:checkStatusDiv,
						checkedDesc:checkedDesc,
						redoBtn:redoBtn
					})
				});
			}
		});
	}
	showModel=(text)=>{
		this.setState({
			operationDetailsVisible:true,
			checkStatus:text.checkStatus,
			checkedDetailParams:{id:text.id,stubGroupId:text.stubGroupId}
		},()=>{
			this.getCheckedInfo()
		})
	}
	closeModel=()=>{
		this.setState({
			operationDetailsVisible:false
		})
	}
	goLink=(text,record,link)=>{
		if(this.props.location.state&&this.props.location.state.stubGroupId){
			sessionManager.set('stubGroupId', this.props.location.state.stubGroupId);
		}
		this.props.history.push({pathname: `/powerStation/${link}`});
	};
	redoBill=()=>{
		axios.get('/api/stubGroup/billSplit/cancleSplitRule',{ params:{stubGroupId: this.state.checkedDetailParams.stubGroupId}}).then(res => {
			if(res&&res.code=='200'){
				message.success('撤回成功');
				this.setState({
					checkedRefresh:this.state.checkedRefresh+1
				})
				this.closeModel()
			}
		})
	}
	getTableInfo(){
		axios.get('/api/stubGroup/billSplit/splitRuleList',{ params:this.state.params}).then(res => {
			if(res&&res.data){
				console.log('点击修改规则--调表格接口',res.data);
				// message.success('撤回成功');
				this.setState({
					editableDataCopy:res.data
				},()=>{
					this.addTabPane()
				})
			}
		})
	}
	add = () => {
		this.getTableInfo();
		this.addTabPane()//先产生tab,等有数据再重新展示tab
	}
	deleteRowdata = (text,record,index) => {
		const dataSource = [...this.state.editableDataCopy];
		console.log(this.state.editableDataCopy);
		this.setState({
			editableDataCopy:dataSource.filter((item,i)=>item.unique!==record)
		},()=>{
			this.addTabPane()
			console.log('删除---',this.state.editableDataCopy)
		})
	}
	handleAdd = () => {
		const { count, editableDataCopy } = this.state;
		const l = this.state.editableDataCopy.length;
		const newData = [{
			billType: '0',
			splitPeriod: '1',
			billUserAccount: '',
			billUserName:'',
			expressionType:'1',
			expressionInfo:'',
			unique: l + 1
		}];
		this.setState({
			editableDataCopy: editableDataCopy.concat(newData),
			count: count + 1,
		},()=>{
			this.addTabPane();
			console.log('增加一条',this.state.editableDataCopy)
		});

	};
	addTabPane(){
		// const panes = this.state.panes;
		this.setState({
			panes:[
				<TabPane tab="修改规则" key="3" closable={true}>
					<Table  columns={this.editableColumns} dataSource={this.state.editableDataCopy}   className="edit-table" pagination={false} />
					<div className="textCenter padT-10 center-btns">
						<Button type="default" onClick={this.handleAdd}>+ 增加一条</Button>
						<Button type="primary" className="ok-btn" onClick={this.saveNewRowData}>保存并提交审核</Button>
					</div>
				</TabPane>
			],
			activeKey:'3'
		})
		// this.setState({ activeKey:'3' });
	}

	saveNewRowData=()=>{
		axios.post('/api/stubGroup/billSplit/addSplitRule',{
			stubGroupId: this.state.params.stubGroupId,
			splitList:JSON.stringify(this.state.editableDataCopy)
		}).then(res=>{
			if(res&&res.code=='200'){
				this.setState({
					checkedRefresh:this.state.checkedRefresh+1 //刷新审核履历
				})
				// this.getTableInfo();
				message.success('修改成功')

			}
		})
	}

	remove = (targetKey) => {
		let lastIndex;
		this.state.panes.forEach((pane, i) => {
			if (pane.key === targetKey) {
				lastIndex = i - 1;
			}
		});
		const panes = this.state.panes.filter(pane => pane.key !== targetKey);

		this.setState({ panes, activeKey:'1' });
	};
	onEdit = (targetKey, action) => {
		console.log(targetKey, action);
		this[action](targetKey);
	};
	changeTab= (activeKey) => {
		this.setState({ activeKey });
	}
	editRule=()=>{
		if(this.state.panes.length==0){
			this.add();
		}else{
			message.warn('不能重复打开修改规则页面')
		}

	}
	render() {
		return (
			<div>
				<Tabs onChange={this.changeTab} type="editable-card"
					  hideAdd
					  onEdit={this.onEdit}
					  activeKey={this.state.activeKey}>
					<TabPane tab="当前分账规则" key="1" closable={false}>
						<Grid url="api/stubGroup/billSplit/splitRuleList" params={this.state.params} columns={this.columns} refresh={this.state.refresh} pagination={false}/>
						<div className="textCenter">
							<Button type={"primary"} onClick={this.editRule} disabled={this.state.btnDisabled}>修改规则</Button>
						</div>
					</TabPane>
					<TabPane tab="审核履历" key="2" closable={false}>
						<Grid url="api/stubGroup/billSplit/checkedList" params={this.state.params} columns={this.checkedColumns} refresh={this.state.checkedRefresh} width={1200}/>
					</TabPane>
					{this.state.panes}
				</Tabs>
				<SCModal visible={this.state.operationDetailsVisible } handleCancel={this.closeModel} title='操作详情' footer={null} className={"W100"}>
					<Row gutter={16}>
						<Col span={12}>
							<div className="info-row">
								<span>提交时间： {this.state.checkedRuleInfo.applyTime}</span>
								<span>提交人： {this.state.checkedRuleInfo.applyUserName||this.state.checkedRuleInfo.applyUserAccount}</span>
								<span>审核状态： {this.state.checkStatusDiv}</span>
								<span>审核人： {this.state.checkedRuleInfo.adminName||this.state.checkedRuleInfo.adminAccount||'--'}</span>
							</div>
							<Grid url="api/stubGroup/billSplit/checkResultRule" columns={this.columns}  params={this.state.checkedDetailParams} pagination={false}/>
							{this.state.checkedDesc}
						</Col>
						<Col span={12}>
							<div className="info-row">历史记录</div>
							<Grid url="api/stubGroup/billSplit/lastCheckResultRule" columns={this.columns}  params={this.state.checkedDetailParams} pagination={false}/>
							{this.state.redoBtn}
						</Col>
					</Row>
				</SCModal>
			</div>
		)
	}
}

export default injectIntl(ledgerRules);